package com.chen.recruit.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chen.recruit.common.annotation.Log;
import com.chen.recruit.common.api.CommonResult;
import com.chen.recruit.common.enums.BusinessType;
import com.chen.recruit.common.utils.ExcelUtils;
import com.chen.recruit.domain.LoginLog;
import com.chen.recruit.domain.model.PageQuery;
import com.chen.recruit.service.LoginLogService;

import javax.servlet.http.HttpServletResponse;

import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import com.chen.recruit.domain.vo.LoginLogVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.Arrays;

@Api(tags = "登录日志管理 LoginLogController")
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/login-log")
public class LoginLogController {

    private final LoginLogService loginLogService;

    @ApiOperation("删除登录日志")
    @SaCheckPermission("system:login-log:delete")
    @Log(module = "系统管理-登录日志", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public CommonResult delete(@PathVariable Integer[] ids) {
        return loginLogService.removeByIds(Arrays.asList(ids)) ? CommonResult.success() : CommonResult.fail();
    }

    @ApiOperation("查询登录日志列表")
    @SaCheckPermission("system:login-log:list")
    @GetMapping("/list")
    public CommonResult list(LoginLogVo loginLogVo, PageQuery pageQuery) {
        return CommonResult.success(loginLogService.page(pageQuery.build(), buildQueryWrapper(loginLogVo)));
    }

    @ApiOperation("导出登录日志列表")
    @SaCheckPermission("system:login-log:export")
    @Log(module = "系统管理-登录日志", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LoginLogVo vo) {
        ExcelUtils.exportExcel(response, "登录日志记录", LoginLog.class, loginLogService.list(buildQueryWrapper(vo)));
    }

    private LambdaQueryWrapper<LoginLog> buildQueryWrapper(LoginLogVo vo) {
        return Wrappers.<LoginLog>lambdaQuery()
                .eq(ObjectUtil.isNotNull(vo.getStatus()), LoginLog::getStatus, vo.getStatus())
                .like(StringUtils.isNotBlank(vo.getUsername()), LoginLog::getUsername, vo.getUsername())
                .like(StringUtils.isNotBlank(vo.getLocation()), LoginLog::getLocation, vo.getLocation())
                .ge(StringUtils.isNotBlank(vo.getBeginTime()), LoginLog::getLoginTime, vo.getBeginTime())
                .le(StringUtils.isNotBlank(vo.getEndTime()), LoginLog::getLoginTime, vo.getEndTime());
    }

}
